import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { GuardEntity } from '../entities/guard.entity';
import { Repository, UpdateResult } from 'typeorm';
import { Guard } from '../constants/guard.constant';

@Injectable()
export class GuardService {
  constructor(@InjectRepository(GuardEntity) private readonly guardRepository: Repository<GuardEntity>) {}

  /**
   * 创建权限
   * @param name 权限名称
   * @param displayName 显示名称
   */
  async create(name: Guard, displayName: string): Promise<GuardEntity> {
    const guard = new GuardEntity();
    guard.displayName = displayName;
    guard.name = name;

    return this.guardRepository.save(guard);
  }

  /**
   * 更新权限
   * @param uuid 权限Uuid
   * @param name 权限名称
   * @param displayName 权限显示名称
   */
  async update(uuid: string, name: Guard, displayName: string): Promise<UpdateResult> {
    return this.guardRepository.update(uuid, { name: name, displayName: displayName });
  }

  /**
   * 获取权限信息
   * @param uuid 权限Uuid
   */
  async findOneByUuid(uuid: string): Promise<GuardEntity> {
    return this.guardRepository.findOne(uuid);
  }

  /**
   * 根据权限名称获取权限
   * @param name 权限名称
   */
  async findOneByName(name: Guard): Promise<GuardEntity> {
    return this.guardRepository.findOne({ name });
  }

  /**
   * 通过权限Uuid列表获取权限列表
   * @param guardUuidList 权限Uuid列表
   */
  async findAllByUuidList(guardUuidList: string[]): Promise<GuardEntity[]> {
    return this.guardRepository.createQueryBuilder('guards').where('guards.uuid = ANY(:guardUuidList)', { guardUuidList }).getMany();
  }

  /**
   * 通过权限名称列表所有权限列表
   * @param guardNameList 权限名称列表
   */
  async findAllByNameList(guardNameList: string[]): Promise<GuardEntity[]> {
    return this.guardRepository.createQueryBuilder('guards').where('guards.name = ANY(:guardNameList)', { guardNameList }).getMany();
  }

  /** 获取权限列表 */
  async find(): Promise<GuardEntity[]> {
    return this.guardRepository.createQueryBuilder('guards').orderBy('guards.name', 'ASC').getMany();
  }
}
